package com.yl.nettylearning.day03;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author yangl
 */
public class NIOServer {
    public static void main(String[] args) throws Exception{
        //创建一个ServerChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个Selector对象
        Selector selector = Selector.open();
        //绑定一个666端口
        serverSocketChannel.socket().bind(new InetSocketAddress(666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //把serverSocketChannel注册到selector 关心事件 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while (true){
            //等待1秒，如果没有事件发生，返回
            if(selector.select(1000) == 0){
                //没有事件发生
                System.out.println("服务器等待了1秒，无连接");
                continue;
            }
            /**
             * 如果返回的大于0，就获取到相应的selectionKey集合
             * 1、如果返回大于0，表示已经获取到关注的事件
             * 2、selector.selectionKeys()，返回关注的事件集合
             * 通过selectionKeys反向获取通道
             *
             */
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历Set<SelectionKey> 使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){
                //获取到selectionKey
                SelectionKey key = keyIterator.next();
                //根据key对应的通道发生的事件，做相应的处理
                if(key.isAcceptable()){
                    //如果是OP_ACCEPT，说明有新的客户端连接
                    //给该客户端生成一个SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个socketChannel" + socketChannel.hashCode());
                    //将socketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel注册到selector上 ，关注事件为OP_READ，同时给socketChannel关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if(key.isReadable()){
                    //发生OP_READ
                    //通过key反向获取对应的channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("客户端发送的数据：" + new String(buffer.array()));
                }
                //手动从集合中移出掉selectionKey，防止重复操作
                keyIterator.remove();
            }
        }
    }
}
